<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Exceptions\PostTooLargeException;

class ApiException extends Exception
{
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function render($request)
    {
        $error = $this->getMessage();
        $error = $error?:parent::getMessage();
        $error = $error?:'未知错误';
        $e_previous = $this->getPrevious()?:$this;
        while ($e_previous->getPrevious()) { //循环异常，直到获取到最初的一个异常对象
            $e_previous = $e_previous->getPrevious();   //获取前一个异常对象
        }

        if (config('app.env') != 'dev') {
            if ($e_previous instanceof PostTooLargeException){
                $error = '上传内容过大';
            } else if (get_class($e_previous) == 'ErrorException') {
                $error = '该功能正在开发中';
            }
        }

        // 临时解决 错误赋值状态码
        $status = 0;
        if(in_array($this->getCode(), config('params')['response_error_code']))
            $status = $this->getCode();

        $ret = [
            'status'=>$status,
            'info'=>$error,
            'data'=>[],
            'api_version'=>config('basic.api_version'),
            'errorCode'=>$this->getCode(),
        ];
        if (env('APP_DEBUG')) {
            if ($e_previous instanceof ErrorException) {

            }
            
            $ret['__errormore'] = [
                'file'=>$e_previous->getFile(),
                'line'=>$e_previous->getLine(),
                'e_class1'=>get_class($e_previous),
            ];
        }
        return $ret;
    }
}
